package view.interfaces;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;

import Util.Utils;
import business.dao.ClienteDAO;
import business.dao.PedidoDAO;
import business.dao.SaboresDAO;
import business.model.ClienteTO;
import business.model.PedidoTO;
import business.model.PedidosAndamento;
import business.model.PizzasTO;
import business.model.SaboresTO;
import business.model.tableModel.AndamentoTableModel;
import business.model.tableModel.PizzaTableModel;
import business.model.tableModel.SaboresTableModel;
import exception.BusinessException;
import exception.InterfaceException;
import exception.UsuarioException;

public class telaPedido extends JFrame {

	private JPanel contentPane;
	private JTextField txtTelefone;
	private JTable table;
	private JTable tblSabores;
	private JTable tblSaboresSelecionados;
	private JLabel lblValorTotal;
	// -----------------DAO's
	private SaboresDAO saboresDAO = new SaboresDAO();
	private ClienteDAO clienteDAO = new ClienteDAO();
	private PedidoDAO pedidoDAO = new PedidoDAO();
	// -----------------DAO's
	// ------------Table Models
	private SaboresTableModel saboresTableModel;
	private SaboresTableModel saboresTableModelSelecionado;
	private SaboresTableModel saboresTableModelPorPizza;
	private PizzaTableModel pizzaTableModel;
	private AndamentoTableModel andamentoTableModel;
	private AndamentoTableModel finalizadoTableModel;
	// ------------Table Models
	private JTextPane lblNomeCliente;
	private ClienteTO clienteTOPedido;
	private JTable tblPizzas;
	private JTable tblSaboresPizza;
	private PedidoTO pedidoTO = new PedidoTO();
	private List<SaboresTO> saboresTOSelecionados = new ArrayList<SaboresTO>();
	private JTable tblPedidoAndamentos;
	private JTable tblPedidosFinalizados;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					telaPedido frame = new telaPedido();
					frame.setResizable(false);
					frame.setVisible(true);
					// frame.listarSabore();
					// frame.listarAndamento();
					// frame.listarFinalizado();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	private void listarSabore() {
		// TODO Auto-generated method stub
		try {
			saboresTableModel = new SaboresTableModel(saboresDAO.listar(null));
			tblSabores.setModel(saboresTableModel);
		} catch (UsuarioException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterfaceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void somarValorTotal() {
		// TODO Auto-generated method stub
		double valorTotal = 0;
		for (PizzasTO pizzasTO : pedidoTO.getPizzasTOs()) {
			int qtdeSabor = 0;
			double valorAcumulado = 0;
			for (SaboresTO saboresTO : pizzasTO.getSaboresTO()) {
				if (valorAcumulado < saboresTO.getPreco()) {
					valorAcumulado = saboresTO.getPreco();
				}
				qtdeSabor++;
			}

			valorTotal += (valorAcumulado);

		}

		pedidoTO.setValorTotal(valorTotal);
		String valorFormatado = Utils.formatarMoeda(valorTotal);
		lblValorTotal.setText(valorFormatado);

	}

	private void listarAndamento() {
		// TODO Auto-generated method stub

		try {
			List<PedidosAndamento> andamentos = pedidoDAO
					.listarPedidosAndamento();
			andamentoTableModel = new AndamentoTableModel(andamentos);
			tblPedidoAndamentos.setModel(andamentoTableModel);

		} catch (UsuarioException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterfaceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void listarFinalizado() {
		// TODO Auto-generated method stub

		try {
			List<PedidosAndamento> andamentos = pedidoDAO
					.listarPedidosFinalizados();
			finalizadoTableModel = new AndamentoTableModel(andamentos);
			tblPedidosFinalizados.setModel(finalizadoTableModel);

		} catch (UsuarioException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterfaceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Create the frame.
	 */
	public telaPedido() {
		setTitle("Pedido");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 868, 650);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);

		JPanel panel = new JPanel();
		panel.setBorder(new LineBorder(new Color(0, 0, 0)));
		panel.setToolTipText("");

		JLabel lblNovoPedido = new JLabel("Novo Pedido");
		lblNovoPedido.setFont(new Font("Tahoma", Font.BOLD, 14));

		JLabel lblPedidosEmAndamento = new JLabel("Pedidos em Andamento");
		lblPedidosEmAndamento.setFont(new Font("Tahoma", Font.BOLD, 14));

		JLabel lblNewLabel = new JLabel("Consulta de pedidos finalizados hoje");
		lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 14));

		JButton btnNewButton_2 = new JButton("Voltar");
		btnNewButton_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				new telaAtendente().setVisible(true);
				setVisible(false);
			}
		});
		btnNewButton_2.setFont(new Font("Tahoma", Font.BOLD, 12));

		JScrollPane scrollPane_4 = new JScrollPane();

		JScrollPane scrollPane_5 = new JScrollPane();
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane
				.setHorizontalGroup(gl_contentPane
						.createParallelGroup(Alignment.LEADING)
						.addGroup(
								Alignment.TRAILING,
								gl_contentPane
										.createSequentialGroup()
										.addGroup(
												gl_contentPane
														.createParallelGroup(
																Alignment.LEADING)
														.addGroup(
																gl_contentPane
																		.createParallelGroup(
																				Alignment.LEADING)
																		.addGroup(
																				gl_contentPane
																						.createSequentialGroup()
																						.addContainerGap()
																						.addComponent(
																								lblPedidosEmAndamento)
																						.addGap(255))
																		.addGroup(
																				Alignment.TRAILING,
																				gl_contentPane
																						.createSequentialGroup()
																						.addGroup(
																								gl_contentPane
																										.createParallelGroup(
																												Alignment.TRAILING)
																										.addGroup(
																												gl_contentPane
																														.createSequentialGroup()
																														.addGap(10)
																														.addComponent(
																																scrollPane_5,
																																GroupLayout.DEFAULT_SIZE,
																																413,
																																Short.MAX_VALUE))
																										.addGroup(
																												gl_contentPane
																														.createSequentialGroup()
																														.addContainerGap()
																														.addComponent(
																																scrollPane_4,
																																GroupLayout.DEFAULT_SIZE,
																																413,
																																Short.MAX_VALUE)))
																						.addPreferredGap(
																								ComponentPlacement.RELATED)))
														.addGroup(
																gl_contentPane
																		.createSequentialGroup()
																		.addContainerGap()
																		.addComponent(
																				lblNewLabel)
																		.addPreferredGap(
																				ComponentPlacement.RELATED)))
										.addGroup(
												gl_contentPane
														.createParallelGroup(
																Alignment.LEADING,
																false)
														.addGroup(
																gl_contentPane
																		.createSequentialGroup()
																		.addComponent(
																				lblNovoPedido)
																		.addPreferredGap(
																				ComponentPlacement.RELATED,
																				GroupLayout.DEFAULT_SIZE,
																				Short.MAX_VALUE)
																		.addComponent(
																				btnNewButton_2,
																				GroupLayout.PREFERRED_SIZE,
																				83,
																				GroupLayout.PREFERRED_SIZE))
														.addGroup(
																Alignment.TRAILING,
																gl_contentPane
																		.createSequentialGroup()
																		.addComponent(
																				panel,
																				GroupLayout.PREFERRED_SIZE,
																				403,
																				GroupLayout.PREFERRED_SIZE)
																		.addGap(10)))));
		gl_contentPane
				.setVerticalGroup(gl_contentPane
						.createParallelGroup(Alignment.LEADING)
						.addGroup(
								gl_contentPane
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												gl_contentPane
														.createParallelGroup(
																Alignment.BASELINE)
														.addComponent(
																btnNewButton_2)
														.addComponent(
																lblPedidosEmAndamento)
														.addComponent(
																lblNovoPedido))
										.addGap(8)
										.addGroup(
												gl_contentPane
														.createParallelGroup(
																Alignment.LEADING)
														.addGroup(
																gl_contentPane
																		.createSequentialGroup()
																		.addComponent(
																				scrollPane_4,
																				GroupLayout.PREFERRED_SIZE,
																				179,
																				GroupLayout.PREFERRED_SIZE)
																		.addGap(11)
																		.addComponent(
																				lblNewLabel)
																		.addPreferredGap(
																				ComponentPlacement.RELATED)
																		.addComponent(
																				scrollPane_5,
																				GroupLayout.DEFAULT_SIZE,
																				336,
																				Short.MAX_VALUE))
														.addComponent(
																panel,
																GroupLayout.DEFAULT_SIZE,
																549,
																Short.MAX_VALUE))
										.addContainerGap()));

		tblPedidosFinalizados = new JTable();
		scrollPane_5.setViewportView(tblPedidosFinalizados);

		tblPedidoAndamentos = new JTable();
		scrollPane_4.setViewportView(tblPedidoAndamentos);

		JTextPane txtpnCliente = new JTextPane();
		txtpnCliente.setBounds(15, 12, 103, 20);
		txtpnCliente.setBackground(SystemColor.control);
		txtpnCliente.setText("Telefone do Cliente:");

		txtTelefone = new JTextField();
		txtTelefone.setBounds(124, 12, 107, 20);
		txtTelefone.setFont(new Font("Tahoma", Font.BOLD, 12));
		txtTelefone.setColumns(10);

		JButton btnFinalizar = new JButton("Finalizar");
		btnFinalizar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					pedidoTO.setCliente(clienteTOPedido);
					pedidoDAO.incluir(pedidoTO);
					pedidoTO = new PedidoTO();
					txtTelefone.setText("");
					lblNomeCliente.setText("");
					pizzaTableModel = new PizzaTableModel(
							new ArrayList<PizzasTO>());
					tblPizzas.setModel(pizzaTableModel);
					listarAndamento();
				} catch (UsuarioException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (BusinessException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (InterfaceException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		btnFinalizar.setBounds(11, 349, 91, 23);
		btnFinalizar.setFont(new Font("Tahoma", Font.BOLD, 12));

		JButton btnLocalizar = new JButton("Localizar");
		btnLocalizar.setBounds(237, 12, 96, 23);
		btnLocalizar.setFont(new Font("Tahoma", Font.PLAIN, 11));
		btnLocalizar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					clienteTOPedido = new ClienteTO();
					clienteTOPedido.setTelefone(txtTelefone.getText());
					clienteTOPedido = clienteDAO.consultar(clienteTOPedido);
					lblNomeCliente.setText(clienteTOPedido.getNome());

				} catch (UsuarioException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (BusinessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InterfaceException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		table = new JTable();
		table.setBounds(11, 440, 383, 104);
		table.setBorder(new LineBorder(new Color(0, 0, 0)));
		table.setModel(new DefaultTableModel(new Object[][] { {}, },
				new String[] {}));

		JLabel lblNewLabel_1 = new JLabel("Hist\u00F3rico de Pedidos");
		lblNewLabel_1.setBounds(11, 414, 125, 15);
		lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 12));

		JLabel lblVslo = new JLabel("Valor: ");
		lblVslo.setBounds(11, 383, 54, 20);
		lblVslo.setForeground(Color.RED);
		lblVslo.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 16));

		lblValorTotal = new JLabel("R$");
		lblValorTotal.setBounds(75, 382, 112, 21);
		lblValorTotal.setFont(new Font("Tahoma", Font.BOLD, 17));

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(11, 63, 173, 111);

		JScrollPane scrollPane_1 = new JScrollPane();
		scrollPane_1.setBounds(237, 63, 157, 111);

		JButton btnAdiciona = new JButton(">");
		btnAdiciona.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				Boolean existe = Boolean.FALSE;

				if (saboresTableModelSelecionado == null) {
					saboresTableModelSelecionado = new SaboresTableModel(
							new ArrayList<SaboresTO>());
				}

				if (tblSabores.getSelectedRow() >= 0) {
					SaboresTO saborSelecao = saboresTableModel.sabores
							.get(tblSabores.getSelectedRow());

					for (SaboresTO saboresTO : saboresTableModelSelecionado.sabores) {
						if (saborSelecao.getCodigo() == saboresTO.getCodigo()) {
							existe = Boolean.TRUE;
						}
					}

					if (!existe) {
						List<SaboresTO> saboresTOs = saboresTableModelSelecionado.sabores;
						saboresTOs.add(saborSelecao);
						saboresTableModelSelecionado = new SaboresTableModel(
								saboresTOs);
						tblSaboresSelecionados
								.setModel(saboresTableModelSelecionado);
					}
				}
			}
		});
		btnAdiciona.setBounds(190, 91, 41, 23);

		JButton btnRemove = new JButton("<");
		btnRemove.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {

				if (tblSaboresSelecionados.getSelectedRow() >= 0) {
					SaboresTO saborExcluido = saboresTableModelSelecionado.sabores
							.get(tblSaboresSelecionados.getSelectedRow());
					List<SaboresTO> saboresTOSelecionadosTMP = saboresTableModelSelecionado.sabores;
					List<SaboresTO> saboresTOs = new ArrayList<SaboresTO>();
					for (SaboresTO to : saboresTOSelecionadosTMP) {
						if (to.getCodigo() != saborExcluido.getCodigo()) {
							saboresTOs.add(to);
						}
					}
					saboresTableModelSelecionado = new SaboresTableModel(
							saboresTOs);
					tblSaboresSelecionados
							.setModel(saboresTableModelSelecionado);

				}
			}
		});
		btnRemove.setBounds(190, 120, 41, 23);

		JTextPane txtpnNomeCliente = new JTextPane();
		txtpnNomeCliente.setBounds(45, 32, 73, 20);
		txtpnNomeCliente.setText("Nome Cliente:");
		txtpnNomeCliente.setBackground(SystemColor.menu);

		lblNomeCliente = new JTextPane();
		lblNomeCliente.setBounds(123, 32, 73, 20);
		lblNomeCliente.setText("N/A");
		lblNomeCliente.setBackground(SystemColor.menu);

		tblSaboresSelecionados = new JTable();
		scrollPane_1.setViewportView(tblSaboresSelecionados);

		tblSabores = new JTable();
		scrollPane.setViewportView(tblSabores);
		panel.setLayout(null);
		panel.add(lblVslo);
		panel.add(btnFinalizar);
		panel.add(lblValorTotal);
		panel.add(lblNewLabel_1);
		panel.add(scrollPane);
		panel.add(btnAdiciona);
		panel.add(btnRemove);
		panel.add(scrollPane_1);
		panel.add(table);
		panel.add(txtpnCliente);
		panel.add(txtpnNomeCliente);
		panel.add(lblNomeCliente);
		panel.add(txtTelefone);
		panel.add(btnLocalizar);

		JScrollPane scrollPane_2 = new JScrollPane();
		scrollPane_2.setBounds(11, 230, 144, 108);
		panel.add(scrollPane_2);

		tblPizzas = new JTable();
		tblPizzas.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				if (arg0.getClickCount() == 2) {
					int indice = tblPizzas.getSelectedRow();
					PizzasTO to = pedidoTO.getPizzasTOs().get(indice);
					saboresTableModelPorPizza = new SaboresTableModel(to
							.getSaboresTO());
					tblSaboresPizza.setModel(saboresTableModelPorPizza);

				}
			}
		});
		scrollPane_2.setViewportView(tblPizzas);

		JScrollPane scrollPane_3 = new JScrollPane();
		scrollPane_3.setBounds(165, 230, 229, 108);
		panel.add(scrollPane_3);

		tblSaboresPizza = new JTable();
		scrollPane_3.setViewportView(tblSaboresPizza);

		JButton btnFinalizarPizza = new JButton("Adicionar Pizza");
		btnFinalizarPizza.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				List<SaboresTO> saboresSelecionados = saboresTableModelSelecionado.sabores;
				PizzasTO pizzasTO = new PizzasTO();
				pizzasTO.getSaboresTO().addAll(saboresSelecionados);
				pedidoTO.getPizzasTOs().add(pizzasTO);

				saboresTableModelSelecionado = new SaboresTableModel(
						new ArrayList<SaboresTO>());
				tblSaboresSelecionados.setModel(saboresTableModelSelecionado);
				pizzaTableModel = new PizzaTableModel(pedidoTO.getPizzasTOs());
				tblPizzas.setModel(pizzaTableModel);

				somarValorTotal();

			}
		});
		btnFinalizarPizza.setFont(new Font("Tahoma", Font.BOLD, 11));
		btnFinalizarPizza.setBounds(247, 185, 144, 23);
		panel.add(btnFinalizarPizza);
		contentPane.setLayout(gl_contentPane);

		listarSabore();
		listarAndamento();
		listarFinalizado();
		finalizadoTableModel = new AndamentoTableModel(
				new ArrayList<PedidosAndamento>());
		tblPedidosFinalizados.setModel(finalizadoTableModel);

		saboresTableModelSelecionado = new SaboresTableModel(
				new ArrayList<SaboresTO>());
		tblSaboresSelecionados.setModel(saboresTableModelSelecionado);

		saboresTableModelPorPizza = new SaboresTableModel(
				new ArrayList<SaboresTO>());
		tblSaboresPizza.setModel(saboresTableModelPorPizza);

		pizzaTableModel = new PizzaTableModel(new ArrayList<PizzasTO>());
		tblPizzas.setModel(pizzaTableModel);

	}
}
